<template>
  <div class="role-management-container">
    <PageHeader title="角色管理">
      <template #actions>
        <el-button type="primary" @click="showAddRoleDialog">
          <el-icon><Plus /></el-icon>
          添加角色
        </el-button>
      </template>
    </PageHeader>

    <main class="role-management-content">
      <el-card class="role-table-card">
      <el-table
        :data="roles"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="权限" width="300">
          <template #default="scope">
            <div class="permission-tags">
              <el-tag
                v-for="permission in scope.row.permissions"
                :key="permission"
                class="permission-tag"
                type="success"
                size="small"
              >
                {{ permission }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="editRole(scope.row)"
              :disabled="scope.row.name === 'admin'"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="confirmDeleteRole(scope.row)"
              :disabled="scope.row.name === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      :title="isEdit ? '编辑角色' : '添加角色'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        :model="roleForm"
        :rules="roleRules"
        ref="roleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-checkbox-group v-model="roleForm.permissions">
            <el-checkbox
              v-for="permission in permissions"
              :key="permission.name"
              :label="permission.name"
            >
              {{ permission.description || permission.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/services/api'
import PageHeader from '@/components/PageHeader.vue'

// 状态
const roles = ref([])
const permissions = ref([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const roleFormRef = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  permissions: []
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度应为2-20个字符', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: '请选择至少一个权限', trigger: 'change' }
  ]
}

// 初始化
onMounted(async () => {
  await fetchRoles()
  await fetchPermissions()
})

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    const response = await api.getRoles()
    roles.value = response.data.roles
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const response = await api.getPermissions()
    permissions.value = response.data.permissions
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 显示添加角色对话框
const showAddRoleDialog = () => {
  isEdit.value = false
  resetRoleForm()
  dialogVisible.value = true
}

// 编辑角色
const editRole = (role) => {
  isEdit.value = true
  resetRoleForm()

  // 填充表单数据
  roleForm.id = role.id
  roleForm.name = role.name
  roleForm.description = role.description
  roleForm.permissions = role.permissions

  dialogVisible.value = true
}

// 重置角色表单
const resetRoleForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }

  roleForm.id = null
  roleForm.name = ''
  roleForm.description = ''
  roleForm.permissions = []
}

// 保存角色
const saveRole = async () => {
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()

    saving.value = true

    if (isEdit.value) {
      // 更新角色
      const roleData = {
        name: roleForm.name,
        description: roleForm.description,
        permissions: roleForm.permissions
      }

      await api.updateRole(roleForm.id, roleData)
      ElMessage.success('角色更新成功')
    } else {
      // 创建角色
      const roleData = {
        name: roleForm.name,
        description: roleForm.description,
        permissions: roleForm.permissions
      }

      await api.createRole(roleData)
      ElMessage.success('角色创建成功')
    }

    // 刷新角色列表
    await fetchRoles()
    dialogVisible.value = false
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error(error.response?.data?.message || '保存角色失败')
  } finally {
    saving.value = false
  }
}

// 确认删除角色
const confirmDeleteRole = (role) => {
  ElMessageBox.confirm(
    `确定要删除角色 "${role.name}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      deleteRole(role.id)
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 删除角色
const deleteRole = async (roleId) => {
  loading.value = true
  try {
    await api.deleteRole(roleId)
    ElMessage.success('角色删除成功')
    await fetchRoles()
  } catch (error) {
    console.error('删除角色失败:', error)
    ElMessage.error(error.response?.data?.message || '删除角色失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.role-management-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.role-management-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 使用共享的 PageHeader 组件样式 */

.role-table-card {
  margin-bottom: 20px;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.permission-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
